home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / cookielib.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2005-10-18  |  52.1 KB  |  1,816 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. """HTTP cookie handling for web clients.
  5.  
  6. This module has (now fairly distant) origins in Gisle Aas' Perl module
  7. HTTP::Cookies, from the libwww-perl library.
  8.  
  9. Docstrings, comments and debug strings in this code refer to the
  10. attributes of the HTTP cookie system as cookie-attributes, to distinguish
  11. them clearly from Python attributes.
  12.  
  13. Class diagram (note that the classes which do not derive from
  14. FileCookieJar are not distributed with the Python standard library, but
  15. are available from http://wwwsearch.sf.net/):
  16.  
  17.                         CookieJar____
  18.                         /     \\                  FileCookieJar      \\                   /    |   \\         \\       MozillaCookieJar | LWPCookieJar \\                        |               |                        |   ---MSIEBase |                         |  /      |     |                          | /   MSIEDBCookieJar BSDDBCookieJar
  19.                   |/
  20.                MSIECookieJar
  21.  
  22. """
  23. import sys
  24. import re
  25. import urlparse
  26. import copy
  27. import time
  28. import urllib
  29. import logging
  30. from types import StringTypes
  31.  
  32. try:
  33.     import threading as _threading
  34. except ImportError:
  35.     import dummy_threading as _threading
  36.  
  37. import httplib
  38. from calendar import timegm
  39. debug = logging.getLogger('cookielib').debug
  40. DEFAULT_HTTP_PORT = str(httplib.HTTP_PORT)
  41. MISSING_FILENAME_TEXT = 'a filename was not supplied (nor was the CookieJar instance initialised with one)'
  42.  
  43. def reraise_unmasked_exceptions(unmasked = ()):
  44.     unmasked = unmasked + (KeyboardInterrupt, SystemExit, MemoryError)
  45.     etype = sys.exc_info()[0]
  46.     if issubclass(etype, unmasked):
  47.         raise 
  48.     
  49.     import warnings
  50.     import traceback
  51.     import StringIO
  52.     f = StringIO.StringIO()
  53.     traceback.print_exc(None, f)
  54.     msg = f.getvalue()
  55.     warnings.warn('cookielib bug!\n%s' % msg, stacklevel = 2)
  56.  
  57. EPOCH_YEAR = 1970
  58.  
  59. def _timegm(tt):
  60.     (year, month, mday, hour, min, sec) = tt[:6]
  61.     if year >= EPOCH_YEAR:
  62.         if month <= month:
  63.             pass
  64.         elif month <= 12:
  65.             if mday <= mday:
  66.                 pass
  67.             elif mday <= 31:
  68.                 if hour <= hour:
  69.                     pass
  70.                 elif hour <= 24:
  71.                     if min <= min:
  72.                         pass
  73.                     elif min <= 59:
  74.                         if sec <= sec:
  75.                             pass
  76.                         elif sec <= 61:
  77.                             return timegm(tt)
  78.                         else:
  79.                             return None
  80.  
  81. DAYS = [
  82.     'Mon',
  83.     'Tue',
  84.     'Wed',
  85.     'Thu',
  86.     'Fri',
  87.     'Sat',
  88.     'Sun']
  89. MONTHS = [
  90.     'Jan',
  91.     'Feb',
  92.     'Mar',
  93.     'Apr',
  94.     'May',
  95.     'Jun',
  96.     'Jul',
  97.     'Aug',
  98.     'Sep',
  99.     'Oct',
  100.     'Nov',
  101.     'Dec']
  102. MONTHS_LOWER = []
  103. for month in MONTHS:
  104.     MONTHS_LOWER.append(month.lower())
  105.  
  106.  
  107. def time2isoz(t = None):
  108.     '''Return a string representing time in seconds since epoch, t.
  109.  
  110.     If the function is called without an argument, it will use the current
  111.     time.
  112.  
  113.     The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
  114.     representing Universal Time (UTC, aka GMT).  An example of this format is:
  115.  
  116.     1994-11-24 08:49:37Z
  117.  
  118.     '''
  119.     if t is None:
  120.         t = time.time()
  121.     
  122.     (year, mon, mday, hour, min, sec) = time.gmtime(t)[:6]
  123.     return '%04d-%02d-%02d %02d:%02d:%02dZ' % (year, mon, mday, hour, min, sec)
  124.  
  125.  
  126. def time2netscape(t = None):
  127.     '''Return a string representing time in seconds since epoch, t.
  128.  
  129.     If the function is called without an argument, it will use the current
  130.     time.
  131.  
  132.     The format of the returned string is like this:
  133.  
  134.     Wed, DD-Mon-YYYY HH:MM:SS GMT
  135.  
  136.     '''
  137.     if t is None:
  138.         t = time.time()
  139.     
  140.     (year, mon, mday, hour, min, sec, wday) = time.gmtime(t)[:7]
  141.     return '%s %02d-%s-%04d %02d:%02d:%02d GMT' % (DAYS[wday], mday, MONTHS[mon - 1], year, hour, min, sec)
  142.  
  143. UTC_ZONES = {
  144.     'GMT': None,
  145.     'UTC': None,
  146.     'UT': None,
  147.     'Z': None }
  148. TIMEZONE_RE = re.compile('^([-+])?(\\d\\d?):?(\\d\\d)?$')
  149.  
  150. def offset_from_tz_string(tz):
  151.     offset = None
  152.     if tz in UTC_ZONES:
  153.         offset = 0
  154.     else:
  155.         m = TIMEZONE_RE.search(tz)
  156.         if m:
  157.             offset = 3600 * int(m.group(2))
  158.             if m.group(3):
  159.                 offset = offset + 60 * int(m.group(3))
  160.             
  161.             if m.group(1) == '-':
  162.                 offset = -offset
  163.             
  164.         
  165.     return offset
  166.  
  167.  
  168. def _str2time(day, mon, yr, hr, min, sec, tz):
  169.     
  170.     try:
  171.         mon = MONTHS_LOWER.index(mon.lower()) + 1
  172.     except ValueError:
  173.         
  174.         try:
  175.             imon = int(mon)
  176.         except ValueError:
  177.             return None
  178.  
  179.         if imon <= imon:
  180.             pass
  181.         elif imon <= 12:
  182.             mon = imon
  183.         else:
  184.             return None
  185.     except:
  186.         1
  187.  
  188.     if hr is None:
  189.         hr = 0
  190.     
  191.     if min is None:
  192.         min = 0
  193.     
  194.     if sec is None:
  195.         sec = 0
  196.     
  197.     yr = int(yr)
  198.     day = int(day)
  199.     hr = int(hr)
  200.     min = int(min)
  201.     sec = int(sec)
  202.     if yr < 1000:
  203.         cur_yr = time.localtime(time.time())[0]
  204.         m = cur_yr % 100
  205.         tmp = yr
  206.         yr = yr + cur_yr - m
  207.         m = m - tmp
  208.         if abs(m) > 50:
  209.             if m > 0:
  210.                 yr = yr + 100
  211.             else:
  212.                 yr = yr - 100
  213.         
  214.     
  215.     t = _timegm((yr, mon, day, hr, min, sec, tz))
  216.     if t is not None:
  217.         if tz is None:
  218.             tz = 'UTC'
  219.         
  220.         tz = tz.upper()
  221.         offset = offset_from_tz_string(tz)
  222.         if offset is None:
  223.             return None
  224.         
  225.         t = t - offset
  226.     
  227.     return t
  228.  
  229. STRICT_DATE_RE = re.compile('^[SMTWF][a-z][a-z], (\\d\\d) ([JFMASOND][a-z][a-z]) (\\d\\d\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$')
  230. WEEKDAY_RE = re.compile('^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\\s*', re.I)
  231. LOOSE_HTTP_DATE_RE = re.compile('^\n    (\\d\\d?)            # day\n       (?:\\s+|[-\\/])\n    (\\w+)              # month\n        (?:\\s+|[-\\/])\n    (\\d+)              # year\n    (?:\n          (?:\\s+|:)    # separator before clock\n       (\\d\\d?):(\\d\\d)  # hour:min\n       (?::(\\d\\d))?    # optional seconds\n    )?                 # optional clock\n       \\s*\n    ([-+]?\\d{2,4}|(?![APap][Mm]\\b)[A-Za-z]+)? # timezone\n       \\s*\n    (?:\\(\\w+\\))?       # ASCII representation of timezone in parens.\n       \\s*$', re.X)
  232.  
  233. def http2time(text):
  234.     '''Returns time in seconds since epoch of time represented by a string.
  235.  
  236.     Return value is an integer.
  237.  
  238.     None is returned if the format of str is unrecognized, the time is outside
  239.     the representable range, or the timezone string is not recognized.  If the
  240.     string contains no timezone, UTC is assumed.
  241.  
  242.     The timezone in the string may be numerical (like "-0800" or "+0100") or a
  243.     string timezone (like "UTC", "GMT", "BST" or "EST").  Currently, only the
  244.     timezone strings equivalent to UTC (zero offset) are known to the function.
  245.  
  246.     The function loosely parses the following formats:
  247.  
  248.     Wed, 09 Feb 1994 22:23:32 GMT       -- HTTP format
  249.     Tuesday, 08-Feb-94 14:15:29 GMT     -- old rfc850 HTTP format
  250.     Tuesday, 08-Feb-1994 14:15:29 GMT   -- broken rfc850 HTTP format
  251.     09 Feb 1994 22:23:32 GMT            -- HTTP format (no weekday)
  252.     08-Feb-94 14:15:29 GMT              -- rfc850 format (no weekday)
  253.     08-Feb-1994 14:15:29 GMT            -- broken rfc850 format (no weekday)
  254.  
  255.     The parser ignores leading and trailing whitespace.  The time may be
  256.     absent.
  257.  
  258.     If the year is given with only 2 digits, the function will select the
  259.     century that makes the year closest to the current date.
  260.  
  261.     '''
  262.     m = STRICT_DATE_RE.search(text)
  263.     if m:
  264.         g = m.groups()
  265.         mon = MONTHS_LOWER.index(g[1].lower()) + 1
  266.         tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5]))
  267.         return _timegm(tt)
  268.     
  269.     text = text.lstrip()
  270.     text = WEEKDAY_RE.sub('', text, 1)
  271.     (day, mon, yr, hr, min, sec, tz) = [
  272.         None] * 7
  273.     m = LOOSE_HTTP_DATE_RE.search(text)
  274.     if m is not None:
  275.         (day, mon, yr, hr, min, sec, tz) = m.groups()
  276.     else:
  277.         return None
  278.     return _str2time(day, mon, yr, hr, min, sec, tz)
  279.  
  280. ISO_DATE_RE = re.compile('^\n    (\\d{4})              # year\n       [-\\/]?\n    (\\d\\d?)              # numerical month\n       [-\\/]?\n    (\\d\\d?)              # day\n   (?:\n         (?:\\s+|[-:Tt])  # separator before clock\n      (\\d\\d?):?(\\d\\d)    # hour:min\n      (?::?(\\d\\d(?:\\.\\d*)?))?  # optional seconds (and fractional)\n   )?                    # optional clock\n      \\s*\n   ([-+]?\\d\\d?:?(:?\\d\\d)?\n    |Z|z)?               # timezone  (Z is "zero meridian", i.e. GMT)\n      \\s*$', re.X)
  281.  
  282. def iso2time(text):
  283.     '''
  284.     As for http2time, but parses the ISO 8601 formats:
  285.  
  286.     1994-02-03 14:15:29 -0100    -- ISO 8601 format
  287.     1994-02-03 14:15:29          -- zone is optional
  288.     1994-02-03                   -- only date
  289.     1994-02-03T14:15:29          -- Use T as separator
  290.     19940203T141529Z             -- ISO 8601 compact format
  291.     19940203                     -- only date
  292.  
  293.     '''
  294.     text = text.lstrip()
  295.     (day, mon, yr, hr, min, sec, tz) = [
  296.         None] * 7
  297.     m = ISO_DATE_RE.search(text)
  298.     if m is not None:
  299.         (yr, mon, day, hr, min, sec, tz, _) = m.groups()
  300.     else:
  301.         return None
  302.     return _str2time(day, mon, yr, hr, min, sec, tz)
  303.  
  304.  
  305. def unmatched(match):
  306.     '''Return unmatched part of re.Match object.'''
  307.     (start, end) = match.span(0)
  308.     return match.string[:start] + match.string[end:]
  309.  
  310. HEADER_TOKEN_RE = re.compile('^\\s*([^=\\s;,]+)')
  311. HEADER_QUOTED_VALUE_RE = re.compile('^\\s*=\\s*\\"([^\\"\\\\]*(?:\\\\.[^\\"\\\\]*)*)\\"')
  312. HEADER_VALUE_RE = re.compile('^\\s*=\\s*([^\\s;,]*)')
  313. HEADER_ESCAPE_RE = re.compile('\\\\(.)')
  314.  
  315. def split_header_words(header_values):
  316.     '''Parse header values into a list of lists containing key,value pairs.
  317.  
  318.     The function knows how to deal with ",", ";" and "=" as well as quoted
  319.     values after "=".  A list of space separated tokens are parsed as if they
  320.     were separated by ";".
  321.  
  322.     If the header_values passed as argument contains multiple values, then they
  323.     are treated as if they were a single value separated by comma ",".
  324.  
  325.     This means that this function is useful for parsing header fields that
  326.     follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
  327.     the requirement for tokens).
  328.  
  329.       headers           = #header
  330.       header            = (token | parameter) *( [";"] (token | parameter))
  331.  
  332.       token             = 1*<any CHAR except CTLs or separators>
  333.       separators        = "(" | ")" | "<" | ">" | "@"
  334.                         | "," | ";" | ":" | "\\" | <">
  335.                         | "/" | "[" | "]" | "?" | "="
  336.                         | "{" | "}" | SP | HT
  337.  
  338.       quoted-string     = ( <"> *(qdtext | quoted-pair ) <"> )
  339.       qdtext            = <any TEXT except <">>
  340.       quoted-pair       = "\\" CHAR
  341.  
  342.       parameter         = attribute "=" value
  343.       attribute         = token
  344.       value             = token | quoted-string
  345.  
  346.     Each header is represented by a list of key/value pairs.  The value for a
  347.     simple token (not part of a parameter) is None.  Syntactically incorrect
  348.     headers will not necessarily be parsed as you would want.
  349.  
  350.     This is easier to describe with some examples:
  351.  
  352.     >>> split_header_words([\'foo="bar"; port="80,81"; discard, bar=baz\'])
  353.     [[(\'foo\', \'bar\'), (\'port\', \'80,81\'), (\'discard\', None)], [(\'bar\', \'baz\')]]
  354.     >>> split_header_words([\'text/html; charset="iso-8859-1"\'])
  355.     [[(\'text/html\', None), (\'charset\', \'iso-8859-1\')]]
  356.     >>> split_header_words([r\'Basic realm="\\"foo\\bar\\""\'])
  357.     [[(\'Basic\', None), (\'realm\', \'"foobar"\')]]
  358.  
  359.     '''
  360.     result = []
  361.     for text in header_values:
  362.         orig_text = text
  363.         pairs = []
  364.         while text:
  365.             m = HEADER_TOKEN_RE.search(text)
  366.             if m:
  367.                 text = unmatched(m)
  368.                 name = m.group(1)
  369.                 m = HEADER_QUOTED_VALUE_RE.search(text)
  370.                 if m:
  371.                     text = unmatched(m)
  372.                     value = m.group(1)
  373.                     value = HEADER_ESCAPE_RE.sub('\\1', value)
  374.                 else:
  375.                     m = HEADER_VALUE_RE.search(text)
  376.                     if m:
  377.                         text = unmatched(m)
  378.                         value = m.group(1)
  379.                         value = value.rstrip()
  380.                     else:
  381.                         value = None
  382.                 pairs.append((name, value))
  383.                 continue
  384.             if text.lstrip().startswith(','):
  385.                 text = text.lstrip()[1:]
  386.                 if pairs:
  387.                     result.append(pairs)
  388.                 
  389.                 pairs = []
  390.                 continue
  391.             (non_junk, nr_junk_chars) = re.subn('^[=\\s;]*', '', text)
  392.             text = non_junk
  393.         if pairs:
  394.             result.append(pairs)
  395.             continue
  396.     
  397.     return result
  398.  
  399. HEADER_JOIN_ESCAPE_RE = re.compile('([\\"\\\\])')
  400.  
  401. def join_header_words(lists):
  402.     '''Do the inverse (almost) of the conversion done by split_header_words.
  403.  
  404.     Takes a list of lists of (key, value) pairs and produces a single header
  405.     value.  Attribute values are quoted if needed.
  406.  
  407.     >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]])
  408.     \'text/plain; charset="iso-8859/1"\'
  409.     >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]])
  410.     \'text/plain, charset="iso-8859/1"\'
  411.  
  412.     '''
  413.     headers = []
  414.     for pairs in lists:
  415.         attr = []
  416.         for k, v in pairs:
  417.             if v is not None:
  418.                 if not re.search('^\\w+$', v):
  419.                     v = HEADER_JOIN_ESCAPE_RE.sub('\\\\\\1', v)
  420.                     v = '"%s"' % v
  421.                 
  422.                 k = '%s=%s' % (k, v)
  423.             
  424.             attr.append(k)
  425.         
  426.         if attr:
  427.             headers.append('; '.join(attr))
  428.             continue
  429.     
  430.     return ', '.join(headers)
  431.  
  432.  
  433. def parse_ns_headers(ns_headers):
  434.     '''Ad-hoc parser for Netscape protocol cookie-attributes.
  435.  
  436.     The old Netscape cookie format for Set-Cookie can for instance contain
  437.     an unquoted "," in the expires field, so we have to use this ad-hoc
  438.     parser instead of split_header_words.
  439.  
  440.     XXX This may not make the best possible effort to parse all the crap
  441.     that Netscape Cookie headers contain.  Ronald Tschalar\'s HTTPClient
  442.     parser is probably better, so could do worse than following that if
  443.     this ever gives any trouble.
  444.  
  445.     Currently, this is also used for parsing RFC 2109 cookies.
  446.  
  447.     '''
  448.     known_attrs = ('expires', 'domain', 'path', 'secure', 'port', 'max-age')
  449.     result = []
  450.     for ns_header in ns_headers:
  451.         pairs = []
  452.         version_set = False
  453.         for ii, param in enumerate(re.split(';\\s*', ns_header)):
  454.             param = param.rstrip()
  455.             if param == '':
  456.                 continue
  457.             
  458.             if '=' not in param:
  459.                 k = param
  460.                 v = None
  461.             else:
  462.                 (k, v) = re.split('\\s*=\\s*', param, 1)
  463.                 k = k.lstrip()
  464.             if ii != 0:
  465.                 lc = k.lower()
  466.                 if lc in known_attrs:
  467.                     k = lc
  468.                 
  469.                 if k == 'version':
  470.                     version_set = True
  471.                 
  472.                 if k == 'expires':
  473.                     if v.startswith('"'):
  474.                         v = v[1:]
  475.                     
  476.                     if v.endswith('"'):
  477.                         v = v[:-1]
  478.                     
  479.                     v = http2time(v)
  480.                 
  481.             
  482.             pairs.append((k, v))
  483.         
  484.         if pairs:
  485.             if not version_set:
  486.                 pairs.append(('version', '0'))
  487.             
  488.             result.append(pairs)
  489.             continue
  490.     
  491.     return result
  492.  
  493. IPV4_RE = re.compile('\\.\\d+$')
  494.  
  495. def is_HDN(text):
  496.     '''Return True if text is a host domain name.'''
  497.     if IPV4_RE.search(text):
  498.         return False
  499.     
  500.     if text == '':
  501.         return False
  502.     
  503.     if text[0] == '.' or text[-1] == '.':
  504.         return False
  505.     
  506.     return True
  507.  
  508.  
  509. def domain_match(A, B):
  510.     """Return True if domain A domain-matches domain B, according to RFC 2965.
  511.  
  512.     A and B may be host domain names or IP addresses.
  513.  
  514.     RFC 2965, section 1:
  515.  
  516.     Host names can be specified either as an IP address or a HDN string.
  517.     Sometimes we compare one host name with another.  (Such comparisons SHALL
  518.     be case-insensitive.)  Host A's name domain-matches host B's if
  519.  
  520.          *  their host name strings string-compare equal; or
  521.  
  522.          * A is a HDN string and has the form NB, where N is a non-empty
  523.             name string, B has the form .B', and B' is a HDN string.  (So,
  524.             x.y.com domain-matches .Y.com but not Y.com.)
  525.  
  526.     Note that domain-match is not a commutative operation: a.b.c.com
  527.     domain-matches .c.com, but not the reverse.
  528.  
  529.     """
  530.     A = A.lower()
  531.     B = B.lower()
  532.     if A == B:
  533.         return True
  534.     
  535.     if not is_HDN(A):
  536.         return False
  537.     
  538.     i = A.rfind(B)
  539.     if i == -1 or i == 0:
  540.         return False
  541.     
  542.     if not B.startswith('.'):
  543.         return False
  544.     
  545.     if not is_HDN(B[1:]):
  546.         return False
  547.     
  548.     return True
  549.  
  550.  
  551. def liberal_is_HDN(text):
  552.     '''Return True if text is a sort-of-like a host domain name.
  553.  
  554.     For accepting/blocking domains.
  555.  
  556.     '''
  557.     if IPV4_RE.search(text):
  558.         return False
  559.     
  560.     return True
  561.  
  562.  
  563. def user_domain_match(A, B):
  564.     '''For blocking/accepting domains.
  565.  
  566.     A and B may be host domain names or IP addresses.
  567.  
  568.     '''
  569.     A = A.lower()
  570.     B = B.lower()
  571.     if not liberal_is_HDN(A) and liberal_is_HDN(B):
  572.         if A == B:
  573.             return True
  574.         
  575.         return False
  576.     
  577.     initial_dot = B.startswith('.')
  578.     if initial_dot and A.endswith(B):
  579.         return True
  580.     
  581.     if not initial_dot and A == B:
  582.         return True
  583.     
  584.     return False
  585.  
  586. cut_port_re = re.compile(':\\d+$')
  587.  
  588. def request_host(request):
  589.     '''Return request-host, as defined by RFC 2965.
  590.  
  591.     Variation from RFC: returned value is lowercased, for convenient
  592.     comparison.
  593.  
  594.     '''
  595.     url = request.get_full_url()
  596.     host = urlparse.urlparse(url)[1]
  597.     if host == '':
  598.         host = request.get_header('Host', '')
  599.     
  600.     host = cut_port_re.sub('', host, 1)
  601.     return host.lower()
  602.  
  603.  
  604. def eff_request_host(request):
  605.     '''Return a tuple (request-host, effective request-host name).
  606.  
  607.     As defined by RFC 2965, except both are lowercased.
  608.  
  609.     '''
  610.     erhn = req_host = request_host(request)
  611.     if req_host.find('.') == -1 and not IPV4_RE.search(req_host):
  612.         erhn = req_host + '.local'
  613.     
  614.     return (req_host, erhn)
  615.  
  616.  
  617. def request_path(request):
  618.     '''request-URI, as defined by RFC 2965.'''
  619.     url = request.get_full_url()
  620.     (path, parameters, query, frag) = urlparse.urlparse(url)[2:]
  621.     if parameters:
  622.         path = '%s;%s' % (path, parameters)
  623.     
  624.     path = escape_path(path)
  625.     req_path = urlparse.urlunparse(('', '', path, '', query, frag))
  626.     if not req_path.startswith('/'):
  627.         req_path = '/' + req_path
  628.     
  629.     return req_path
  630.  
  631.  
  632. def request_port(request):
  633.     host = request.get_host()
  634.     i = host.find(':')
  635.     if i >= 0:
  636.         port = host[i + 1:]
  637.         
  638.         try:
  639.             int(port)
  640.         except ValueError:
  641.             debug("nonnumeric port: '%s'", port)
  642.             return None
  643.         except:
  644.             None<EXCEPTION MATCH>ValueError
  645.         
  646.  
  647.     None<EXCEPTION MATCH>ValueError
  648.     port = DEFAULT_HTTP_PORT
  649.     return port
  650.  
  651. HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()"
  652. ESCAPED_CHAR_RE = re.compile('%([0-9a-fA-F][0-9a-fA-F])')
  653.  
  654. def uppercase_escaped_char(match):
  655.     return '%%%s' % match.group(1).upper()
  656.  
  657.  
  658. def escape_path(path):
  659.     '''Escape any invalid characters in HTTP URL, and uppercase all escapes.'''
  660.     if isinstance(path, unicode):
  661.         path = path.encode('utf-8')
  662.     
  663.     path = urllib.quote(path, HTTP_PATH_SAFE)
  664.     path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
  665.     return path
  666.  
  667.  
  668. def reach(h):
  669.     '''Return reach of host h, as defined by RFC 2965, section 1.
  670.  
  671.     The reach R of a host name H is defined as follows:
  672.  
  673.        *  If
  674.  
  675.           -  H is the host domain name of a host; and,
  676.  
  677.           -  H has the form A.B; and
  678.  
  679.           -  A has no embedded (that is, interior) dots; and
  680.  
  681.           -  B has at least one embedded dot, or B is the string "local".
  682.              then the reach of H is .B.
  683.  
  684.        *  Otherwise, the reach of H is H.
  685.  
  686.     >>> reach("www.acme.com")
  687.     \'.acme.com\'
  688.     >>> reach("acme.com")
  689.     \'acme.com\'
  690.     >>> reach("acme.local")
  691.     \'.local\'
  692.  
  693.     '''
  694.     i = h.find('.')
  695.     if i >= 0:
  696.         b = h[i + 1:]
  697.         i = b.find('.')
  698.         if is_HDN(h):
  699.             pass
  700.         None if i >= 0 or b == 'local' else b == 'local'
  701.     
  702.     return h
  703.  
  704.  
  705. def is_third_party(request):
  706.     '''
  707.  
  708.     RFC 2965, section 3.3.6:
  709.  
  710.         An unverifiable transaction is to a third-party host if its request-
  711.         host U does not domain-match the reach R of the request-host O in the
  712.         origin transaction.
  713.  
  714.     '''
  715.     req_host = request_host(request)
  716.     if not domain_match(req_host, reach(request.get_origin_req_host())):
  717.         return True
  718.     else:
  719.         return False
  720.  
  721.  
  722. class Cookie:
  723.     '''HTTP Cookie.
  724.  
  725.     This class represents both Netscape and RFC 2965 cookies.
  726.  
  727.     This is deliberately a very simple class.  It just holds attributes.  It\'s
  728.     possible to construct Cookie instances that don\'t comply with the cookie
  729.     standards.  CookieJar.make_cookies is the factory function for Cookie
  730.     objects -- it deals with cookie parsing, supplying defaults, and
  731.     normalising to the representation used in this class.  CookiePolicy is
  732.     responsible for checking them to see whether they should be accepted from
  733.     and returned to the server.
  734.  
  735.     Note that the port may be present in the headers, but unspecified ("Port"
  736.     rather than"Port=80", for example); if this is the case, port is None.
  737.  
  738.     '''
  739.     
  740.     def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest):
  741.         if version is not None:
  742.             version = int(version)
  743.         
  744.         if expires is not None:
  745.             expires = int(expires)
  746.         
  747.         if port is None and port_specified is True:
  748.             raise ValueError('if port is None, port_specified must be false')
  749.         
  750.         self.version = version
  751.         self.name = name
  752.         self.value = value
  753.         self.port = port
  754.         self.port_specified = port_specified
  755.         self.domain = domain.lower()
  756.         self.domain_specified = domain_specified
  757.         self.domain_initial_dot = domain_initial_dot
  758.         self.path = path
  759.         self.path_specified = path_specified
  760.         self.secure = secure
  761.         self.expires = expires
  762.         self.discard = discard
  763.         self.comment = comment
  764.         self.comment_url = comment_url
  765.         self._rest = copy.copy(rest)
  766.  
  767.     
  768.     def has_nonstandard_attr(self, name):
  769.         return name in self._rest
  770.  
  771.     
  772.     def get_nonstandard_attr(self, name, default = None):
  773.         return self._rest.get(name, default)
  774.  
  775.     
  776.     def set_nonstandard_attr(self, name, value):
  777.         self._rest[name] = value
  778.  
  779.     
  780.     def is_expired(self, now = None):
  781.         if now is None:
  782.             now = time.time()
  783.         
  784.         if self.expires is not None and self.expires <= now:
  785.             return True
  786.         
  787.         return False
  788.  
  789.     
  790.     def __str__(self):
  791.         if self.port is None:
  792.             p = ''
  793.         else:
  794.             p = ':' + self.port
  795.         limit = self.domain + p + self.path
  796.         if self.value is not None:
  797.             namevalue = '%s=%s' % (self.name, self.value)
  798.         else:
  799.             namevalue = self.name
  800.         return '<Cookie %s for %s>' % (namevalue, limit)
  801.  
  802.     
  803.     def __repr__(self):
  804.         args = []
  805.         for name in [
  806.             'version',
  807.             'name',
  808.             'value',
  809.             'port',
  810.             'port_specified',
  811.             'domain',
  812.             'domain_specified',
  813.             'domain_initial_dot',
  814.             'path',
  815.             'path_specified',
  816.             'secure',
  817.             'expires',
  818.             'discard',
  819.             'comment',
  820.             'comment_url']:
  821.             attr = getattr(self, name)
  822.             args.append('%s=%s' % (name, repr(attr)))
  823.         
  824.         args.append('rest=%s' % repr(self._rest))
  825.         return 'Cookie(%s)' % ', '.join(args)
  826.  
  827.  
  828.  
  829. class CookiePolicy:
  830.     '''Defines which cookies get accepted from and returned to server.
  831.  
  832.     May also modify cookies, though this is probably a bad idea.
  833.  
  834.     The subclass DefaultCookiePolicy defines the standard rules for Netscape
  835.     and RFC 2965 cookies -- override that if you want a customised policy.
  836.  
  837.     '''
  838.     
  839.     def set_ok(self, cookie, request):
  840.         '''Return true if (and only if) cookie should be accepted from server.
  841.  
  842.         Currently, pre-expired cookies never get this far -- the CookieJar
  843.         class deletes such cookies itself.
  844.  
  845.         '''
  846.         raise NotImplementedError()
  847.  
  848.     
  849.     def return_ok(self, cookie, request):
  850.         '''Return true if (and only if) cookie should be returned to server.'''
  851.         raise NotImplementedError()
  852.  
  853.     
  854.     def domain_return_ok(self, domain, request):
  855.         '''Return false if cookies should not be returned, given cookie domain.
  856.         '''
  857.         return True
  858.  
  859.     
  860.     def path_return_ok(self, path, request):
  861.         '''Return false if cookies should not be returned, given cookie path.
  862.         '''
  863.         return True
  864.  
  865.  
  866.  
  867. class DefaultCookiePolicy(CookiePolicy):
  868.     '''Implements the standard rules for accepting and returning cookies.'''
  869.     DomainStrictNoDots = 1
  870.     DomainStrictNonDomain = 2
  871.     DomainRFC2965Match = 4
  872.     DomainLiberal = 0
  873.     DomainStrict = DomainStrictNoDots | DomainStrictNonDomain
  874.     
  875.     def __init__(self, blocked_domains = None, allowed_domains = None, netscape = True, rfc2965 = False, hide_cookie2 = False, strict_domain = False, strict_rfc2965_unverifiable = True, strict_ns_unverifiable = False, strict_ns_domain = DomainLiberal, strict_ns_set_initial_dollar = False, strict_ns_set_path = False):
  876.         '''Constructor arguments should be passed as keyword arguments only.'''
  877.         self.netscape = netscape
  878.         self.rfc2965 = rfc2965
  879.         self.hide_cookie2 = hide_cookie2
  880.         self.strict_domain = strict_domain
  881.         self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable
  882.         self.strict_ns_unverifiable = strict_ns_unverifiable
  883.         self.strict_ns_domain = strict_ns_domain
  884.         self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar
  885.         self.strict_ns_set_path = strict_ns_set_path
  886.         if blocked_domains is not None:
  887.             self._blocked_domains = tuple(blocked_domains)
  888.         else:
  889.             self._blocked_domains = ()
  890.         if allowed_domains is not None:
  891.             allowed_domains = tuple(allowed_domains)
  892.         
  893.         self._allowed_domains = allowed_domains
  894.  
  895.     
  896.     def blocked_domains(self):
  897.         '''Return the sequence of blocked domains (as a tuple).'''
  898.         return self._blocked_domains
  899.  
  900.     
  901.     def set_blocked_domains(self, blocked_domains):
  902.         '''Set the sequence of blocked domains.'''
  903.         self._blocked_domains = tuple(blocked_domains)
  904.  
  905.     
  906.     def is_blocked(self, domain):
  907.         for blocked_domain in self._blocked_domains:
  908.             if user_domain_match(domain, blocked_domain):
  909.                 return True
  910.                 continue
  911.         
  912.         return False
  913.  
  914.     
  915.     def allowed_domains(self):
  916.         '''Return None, or the sequence of allowed domains (as a tuple).'''
  917.         return self._allowed_domains
  918.  
  919.     
  920.     def set_allowed_domains(self, allowed_domains):
  921.         '''Set the sequence of allowed domains, or None.'''
  922.         if allowed_domains is not None:
  923.             allowed_domains = tuple(allowed_domains)
  924.         
  925.         self._allowed_domains = allowed_domains
  926.  
  927.     
  928.     def is_not_allowed(self, domain):
  929.         if self._allowed_domains is None:
  930.             return False
  931.         
  932.         for allowed_domain in self._allowed_domains:
  933.             if user_domain_match(domain, allowed_domain):
  934.                 return False
  935.                 continue
  936.         
  937.         return True
  938.  
  939.     
  940.     def set_ok(self, cookie, request):
  941.         '''
  942.         If you override .set_ok(), be sure to call this method.  If it returns
  943.         false, so should your subclass (assuming your subclass wants to be more
  944.         strict about which cookies to accept).
  945.  
  946.         '''
  947.         debug(' - checking cookie %s=%s', cookie.name, cookie.value)
  948.         for n in ('version', 'verifiability', 'name', 'path', 'domain', 'port'):
  949.             fn_name = 'set_ok_' + n
  950.             fn = getattr(self, fn_name)
  951.             if not fn(cookie, request):
  952.                 return False
  953.                 continue
  954.         
  955.         return True
  956.  
  957.     
  958.     def set_ok_version(self, cookie, request):
  959.         if cookie.version is None:
  960.             debug('   Set-Cookie2 without version attribute (%s=%s)', cookie.name, cookie.value)
  961.             return False
  962.         
  963.         if cookie.version > 0 and not (self.rfc2965):
  964.             debug('   RFC 2965 cookies are switched off')
  965.             return False
  966.         elif cookie.version == 0 and not (self.netscape):
  967.             debug('   Netscape cookies are switched off')
  968.             return False
  969.         
  970.         return True
  971.  
  972.     
  973.     def set_ok_verifiability(self, cookie, request):
  974.         if request.is_unverifiable() and is_third_party(request):
  975.             if cookie.version > 0 and self.strict_rfc2965_unverifiable:
  976.                 debug('   third-party RFC 2965 cookie during unverifiable transaction')
  977.                 return False
  978.             elif cookie.version == 0 and self.strict_ns_unverifiable:
  979.                 debug('   third-party Netscape cookie during unverifiable transaction')
  980.                 return False
  981.             
  982.         
  983.         return True
  984.  
  985.     
  986.     def set_ok_name(self, cookie, request):
  987.         if cookie.version == 0 and self.strict_ns_set_initial_dollar and cookie.name.startswith('$'):
  988.             debug("   illegal name (starts with '$'): '%s'", cookie.name)
  989.             return False
  990.         
  991.         return True
  992.  
  993.     
  994.     def set_ok_path(self, cookie, request):
  995.         if cookie.path_specified:
  996.             req_path = request_path(request)
  997.             if (cookie.version > 0 or cookie.version == 0 or self.strict_ns_set_path) and not req_path.startswith(cookie.path):
  998.                 debug('   path attribute %s is not a prefix of request path %s', cookie.path, req_path)
  999.                 return False
  1000.             
  1001.         
  1002.         return True
  1003.  
  1004.     
  1005.     def set_ok_domain(self, cookie, request):
  1006.         if self.is_blocked(cookie.domain):
  1007.             debug('   domain %s is in user block-list', cookie.domain)
  1008.             return False
  1009.         
  1010.         if self.is_not_allowed(cookie.domain):
  1011.             debug('   domain %s is not in user allow-list', cookie.domain)
  1012.             return False
  1013.         
  1014.         if cookie.domain_specified:
  1015.             (req_host, erhn) = eff_request_host(request)
  1016.             domain = cookie.domain
  1017.             if self.strict_domain and domain.count('.') >= 2:
  1018.                 i = domain.rfind('.')
  1019.                 j = domain.rfind('.', 0, i)
  1020.                 if j == 0:
  1021.                     tld = domain[i + 1:]
  1022.                     sld = domain[j + 1:i]
  1023.                     if sld.lower() in [
  1024.                         'co',
  1025.                         'ac',
  1026.                         'com',
  1027.                         'edu',
  1028.                         'org',
  1029.                         'net',
  1030.                         'gov',
  1031.                         'mil',
  1032.                         'int'] and len(tld) == 2:
  1033.                         debug('   country-code second level domain %s', domain)
  1034.                         return False
  1035.                     
  1036.                 
  1037.             
  1038.             if domain.startswith('.'):
  1039.                 undotted_domain = domain[1:]
  1040.             else:
  1041.                 undotted_domain = domain
  1042.             embedded_dots = undotted_domain.find('.') >= 0
  1043.             if not embedded_dots and domain != '.local':
  1044.                 debug('   non-local domain %s contains no embedded dot', domain)
  1045.                 return False
  1046.             
  1047.             if cookie.version == 0:
  1048.                 if not erhn.endswith(domain) and not erhn.startswith('.') and not ('.' + erhn).endswith(domain):
  1049.                     debug('   effective request-host %s (even with added initial dot) does not end end with %s', erhn, domain)
  1050.                     return False
  1051.                 
  1052.             
  1053.             if cookie.version > 0 or self.strict_ns_domain & self.DomainRFC2965Match:
  1054.                 if not domain_match(erhn, domain):
  1055.                     debug('   effective request-host %s does not domain-match %s', erhn, domain)
  1056.                     return False
  1057.                 
  1058.             
  1059.             if cookie.version > 0 or self.strict_ns_domain & self.DomainStrictNoDots:
  1060.                 host_prefix = req_host[:-len(domain)]
  1061.                 if host_prefix.find('.') >= 0 and not IPV4_RE.search(req_host):
  1062.                     debug('   host prefix %s for domain %s contains a dot', host_prefix, domain)
  1063.                     return False
  1064.                 
  1065.             
  1066.         
  1067.         return True
  1068.  
  1069.     
  1070.     def set_ok_port(self, cookie, request):
  1071.         if cookie.port_specified:
  1072.             req_port = request_port(request)
  1073.             if req_port is None:
  1074.                 req_port = '80'
  1075.             else:
  1076.                 req_port = str(req_port)
  1077.             for p in cookie.port.split(','):
  1078.                 
  1079.                 try:
  1080.                     int(p)
  1081.                 except ValueError:
  1082.                     debug('   bad port %s (not numeric)', p)
  1083.                     return False
  1084.  
  1085.                 if p == req_port:
  1086.                     break
  1087.                     continue
  1088.             else:
  1089.                 return False
  1090.         
  1091.         return True
  1092.  
  1093.     
  1094.     def return_ok(self, cookie, request):
  1095.         '''
  1096.         If you override .return_ok(), be sure to call this method.  If it
  1097.         returns false, so should your subclass (assuming your subclass wants to
  1098.         be more strict about which cookies to return).
  1099.  
  1100.         '''
  1101.         debug(' - checking cookie %s=%s', cookie.name, cookie.value)
  1102.         for n in ('version', 'verifiability', 'secure', 'expires', 'port', 'domain'):
  1103.             fn_name = 'return_ok_' + n
  1104.             fn = getattr(self, fn_name)
  1105.             if not fn(cookie, request):
  1106.                 return False
  1107.                 continue
  1108.         
  1109.         return True
  1110.  
  1111.     
  1112.     def return_ok_version(self, cookie, request):
  1113.         if cookie.version > 0 and not (self.rfc2965):
  1114.             debug('   RFC 2965 cookies are switched off')
  1115.             return False
  1116.         elif cookie.version == 0 and not (self.netscape):
  1117.             debug('   Netscape cookies are switched off')
  1118.             return False
  1119.         
  1120.         return True
  1121.  
  1122.     
  1123.     def return_ok_verifiability(self, cookie, request):
  1124.         if request.is_unverifiable() and is_third_party(request):
  1125.             if cookie.version > 0 and self.strict_rfc2965_unverifiable:
  1126.                 debug('   third-party RFC 2965 cookie during unverifiable transaction')
  1127.                 return False
  1128.             elif cookie.version == 0 and self.strict_ns_unverifiable:
  1129.                 debug('   third-party Netscape cookie during unverifiable transaction')
  1130.                 return False
  1131.             
  1132.         
  1133.         return True
  1134.  
  1135.     
  1136.     def return_ok_secure(self, cookie, request):
  1137.         if cookie.secure and request.get_type() != 'https':
  1138.             debug('   secure cookie with non-secure request')
  1139.             return False
  1140.         
  1141.         return True
  1142.  
  1143.     
  1144.     def return_ok_expires(self, cookie, request):
  1145.         if cookie.is_expired(self._now):
  1146.             debug('   cookie expired')
  1147.             return False
  1148.         
  1149.         return True
  1150.  
  1151.     
  1152.     def return_ok_port(self, cookie, request):
  1153.         if cookie.port:
  1154.             req_port = request_port(request)
  1155.             if req_port is None:
  1156.                 req_port = '80'
  1157.             
  1158.             for p in cookie.port.split(','):
  1159.                 if p == req_port:
  1160.                     break
  1161.                     continue
  1162.             else:
  1163.                 return False
  1164.         
  1165.         return True
  1166.  
  1167.     
  1168.     def return_ok_domain(self, cookie, request):
  1169.         (req_host, erhn) = eff_request_host(request)
  1170.         domain = cookie.domain
  1171.         if cookie.version == 0 and self.strict_ns_domain & self.DomainStrictNonDomain and not (cookie.domain_specified) and domain != erhn:
  1172.             debug('   cookie with unspecified domain does not string-compare equal to request domain')
  1173.             return False
  1174.         
  1175.         if cookie.version > 0 and not domain_match(erhn, domain):
  1176.             debug('   effective request-host name %s does not domain-match RFC 2965 cookie domain %s', erhn, domain)
  1177.             return False
  1178.         
  1179.         if cookie.version == 0 and not ('.' + erhn).endswith(domain):
  1180.             debug('   request-host %s does not match Netscape cookie domain %s', req_host, domain)
  1181.             return False
  1182.         
  1183.         return True
  1184.  
  1185.     
  1186.     def domain_return_ok(self, domain, request):
  1187.         (req_host, erhn) = eff_request_host(request)
  1188.         if not req_host.startswith('.'):
  1189.             req_host = '.' + req_host
  1190.         
  1191.         if not erhn.startswith('.'):
  1192.             erhn = '.' + erhn
  1193.         
  1194.         if not req_host.endswith(domain) or erhn.endswith(domain):
  1195.             return False
  1196.         
  1197.         if self.is_blocked(domain):
  1198.             debug('   domain %s is in user block-list', domain)
  1199.             return False
  1200.         
  1201.         if self.is_not_allowed(domain):
  1202.             debug('   domain %s is not in user allow-list', domain)
  1203.             return False
  1204.         
  1205.         return True
  1206.  
  1207.     
  1208.     def path_return_ok(self, path, request):
  1209.         debug('- checking cookie path=%s', path)
  1210.         req_path = request_path(request)
  1211.         if not req_path.startswith(path):
  1212.             debug('  %s does not path-match %s', req_path, path)
  1213.             return False
  1214.         
  1215.         return True
  1216.  
  1217.  
  1218.  
  1219. def vals_sorted_by_key(adict):
  1220.     keys = adict.keys()
  1221.     keys.sort()
  1222.     return map(adict.get, keys)
  1223.  
  1224.  
  1225. def deepvalues(mapping):
  1226.     '''Iterates over nested mapping, depth-first, in sorted order by key.'''
  1227.     values = vals_sorted_by_key(mapping)
  1228.     for obj in values:
  1229.         mapping = False
  1230.         
  1231.         try:
  1232.             obj.items
  1233.         except AttributeError:
  1234.             pass
  1235.  
  1236.         mapping = True
  1237.         for subobj in deepvalues(obj):
  1238.             yield subobj
  1239.         
  1240.         if not mapping:
  1241.             yield obj
  1242.             continue
  1243.     
  1244.  
  1245.  
  1246. class Absent:
  1247.     pass
  1248.  
  1249.  
  1250. class CookieJar:
  1251.     '''Collection of HTTP cookies.
  1252.  
  1253.     You may not need to know about this class: try
  1254.     urllib2.build_opener(HTTPCookieProcessor).open(url).
  1255.  
  1256.     '''
  1257.     non_word_re = re.compile('\\W')
  1258.     quote_re = re.compile('([\\"\\\\])')
  1259.     strict_domain_re = re.compile('\\.?[^.]*')
  1260.     domain_re = re.compile('[^.]*')
  1261.     dots_re = re.compile('^\\.+')
  1262.     magic_re = '^\\#LWP-Cookies-(\\d+\\.\\d+)'
  1263.     
  1264.     def __init__(self, policy = None):
  1265.         if policy is None:
  1266.             policy = DefaultCookiePolicy()
  1267.         
  1268.         self._policy = policy
  1269.         self._cookies_lock = _threading.RLock()
  1270.         self._cookies = { }
  1271.  
  1272.     
  1273.     def set_policy(self, policy):
  1274.         self._policy = policy
  1275.  
  1276.     
  1277.     def _cookies_for_domain(self, domain, request):
  1278.         cookies = []
  1279.         if not self._policy.domain_return_ok(domain, request):
  1280.             return []
  1281.         
  1282.         debug('Checking %s for cookies to return', domain)
  1283.         cookies_by_path = self._cookies[domain]
  1284.         for path in cookies_by_path.keys():
  1285.             if not self._policy.path_return_ok(path, request):
  1286.                 continue
  1287.             
  1288.             cookies_by_name = cookies_by_path[path]
  1289.             for cookie in cookies_by_name.values():
  1290.                 if not self._policy.return_ok(cookie, request):
  1291.                     debug('   not returning cookie')
  1292.                     continue
  1293.                 
  1294.                 debug("   it's a match")
  1295.                 cookies.append(cookie)
  1296.             
  1297.         
  1298.         return cookies
  1299.  
  1300.     
  1301.     def _cookies_for_request(self, request):
  1302.         '''Return a list of cookies to be returned to server.'''
  1303.         cookies = []
  1304.         for domain in self._cookies.keys():
  1305.             cookies.extend(self._cookies_for_domain(domain, request))
  1306.         
  1307.         return cookies
  1308.  
  1309.     
  1310.     def _cookie_attrs(self, cookies):
  1311.         '''Return a list of cookie-attributes to be returned to server.
  1312.  
  1313.         like [\'foo="bar"; $Path="/"\', ...]
  1314.  
  1315.         The $Version attribute is also added when appropriate (currently only
  1316.         once per request).
  1317.  
  1318.         '''
  1319.         
  1320.         def decreasing_size(a, b):
  1321.             return cmp(len(b.path), len(a.path))
  1322.  
  1323.         cookies.sort(decreasing_size)
  1324.         version_set = False
  1325.         attrs = []
  1326.         for cookie in cookies:
  1327.             version = cookie.version
  1328.             if not version_set:
  1329.                 version_set = True
  1330.                 if version > 0:
  1331.                     attrs.append('$Version=%s' % version)
  1332.                 
  1333.             
  1334.             if cookie.value is not None and self.non_word_re.search(cookie.value) and version > 0:
  1335.                 value = self.quote_re.sub('\\\\\\1', cookie.value)
  1336.             else:
  1337.                 value = cookie.value
  1338.             if cookie.value is None:
  1339.                 attrs.append(cookie.name)
  1340.             else:
  1341.                 attrs.append('%s=%s' % (cookie.name, value))
  1342.             if version > 0:
  1343.                 if cookie.path_specified:
  1344.                     attrs.append('$Path="%s"' % cookie.path)
  1345.                 
  1346.                 if cookie.domain.startswith('.'):
  1347.                     domain = cookie.domain
  1348.                     if not (cookie.domain_initial_dot) and domain.startswith('.'):
  1349.                         domain = domain[1:]
  1350.                     
  1351.                     attrs.append('$Domain="%s"' % domain)
  1352.                 
  1353.                 if cookie.port is not None:
  1354.                     p = '$Port'
  1355.                     if cookie.port_specified:
  1356.                         p = p + '="%s"' % cookie.port
  1357.                     
  1358.                     attrs.append(p)
  1359.                 
  1360.             cookie.port is not None
  1361.         
  1362.         return attrs
  1363.  
  1364.     
  1365.     def add_cookie_header(self, request):
  1366.         '''Add correct Cookie: header to request (urllib2.Request object).
  1367.  
  1368.         The Cookie2 header is also added unless policy.hide_cookie2 is true.
  1369.  
  1370.         '''
  1371.         debug('add_cookie_header')
  1372.         self._cookies_lock.acquire()
  1373.         self._policy._now = self._now = int(time.time())
  1374.         (req_host, erhn) = eff_request_host(request)
  1375.         strict_non_domain = self._policy.strict_ns_domain & self._policy.DomainStrictNonDomain
  1376.         cookies = self._cookies_for_request(request)
  1377.         attrs = self._cookie_attrs(cookies)
  1378.         if attrs:
  1379.             if not request.has_header('Cookie'):
  1380.                 request.add_unredirected_header('Cookie', '; '.join(attrs))
  1381.             
  1382.         
  1383.         if self._policy.rfc2965 and not (self._policy.hide_cookie2) and not request.has_header('Cookie2'):
  1384.             for cookie in cookies:
  1385.                 if cookie.version != 1:
  1386.                     request.add_unredirected_header('Cookie2', '$Version="1"')
  1387.                     break
  1388.                     continue
  1389.             
  1390.         
  1391.         self._cookies_lock.release()
  1392.         self.clear_expired_cookies()
  1393.  
  1394.     
  1395.     def _normalized_cookie_tuples(self, attrs_set):
  1396.         '''Return list of tuples containing normalised cookie information.
  1397.  
  1398.         attrs_set is the list of lists of key,value pairs extracted from
  1399.         the Set-Cookie or Set-Cookie2 headers.
  1400.  
  1401.         Tuples are name, value, standard, rest, where name and value are the
  1402.         cookie name and value, standard is a dictionary containing the standard
  1403.         cookie-attributes (discard, secure, version, expires or max-age,
  1404.         domain, path and port) and rest is a dictionary containing the rest of
  1405.         the cookie-attributes.
  1406.  
  1407.         '''
  1408.         cookie_tuples = []
  1409.         boolean_attrs = ('discard', 'secure')
  1410.         value_attrs = ('version', 'expires', 'max-age', 'domain', 'path', 'port', 'comment', 'commenturl')
  1411.         for cookie_attrs in attrs_set:
  1412.             (name, value) = cookie_attrs[0]
  1413.             max_age_set = False
  1414.             bad_cookie = False
  1415.             standard = { }
  1416.             rest = { }
  1417.             for k, v in cookie_attrs[1:]:
  1418.                 lc = k.lower()
  1419.                 if lc in value_attrs or lc in boolean_attrs:
  1420.                     k = lc
  1421.                 
  1422.                 if k in boolean_attrs and v is None:
  1423.                     v = True
  1424.                 
  1425.                 if k in standard:
  1426.                     continue
  1427.                 
  1428.                 if k == 'domain':
  1429.                     if v is None:
  1430.                         debug('   missing value for domain attribute')
  1431.                         bad_cookie = True
  1432.                         break
  1433.                     
  1434.                     v = v.lower()
  1435.                 
  1436.                 if k == 'expires':
  1437.                     if max_age_set:
  1438.                         continue
  1439.                     
  1440.                     if v is None:
  1441.                         debug('   missing or invalid value for expires attribute: treating as session cookie')
  1442.                         continue
  1443.                     
  1444.                 
  1445.                 if k == 'max-age':
  1446.                     max_age_set = True
  1447.                     
  1448.                     try:
  1449.                         v = int(v)
  1450.                     except ValueError:
  1451.                         debug('   missing or invalid (non-numeric) value for max-age attribute')
  1452.                         bad_cookie = True
  1453.                         break
  1454.  
  1455.                     k = 'expires'
  1456.                     v = self._now + v
  1457.                 
  1458.                 if k in value_attrs or k in boolean_attrs:
  1459.                     if v is None and k not in [
  1460.                         'port',
  1461.                         'comment',
  1462.                         'commenturl']:
  1463.                         debug('   missing value for %s attribute' % k)
  1464.                         bad_cookie = True
  1465.                         break
  1466.                     
  1467.                     standard[k] = v
  1468.                     continue
  1469.                 rest[k] = v
  1470.             
  1471.             if bad_cookie:
  1472.                 continue
  1473.             
  1474.             cookie_tuples.append((name, value, standard, rest))
  1475.         
  1476.         return cookie_tuples
  1477.  
  1478.     
  1479.     def _cookie_from_cookie_tuple(self, tup, request):
  1480.         (name, value, standard, rest) = tup
  1481.         domain = standard.get('domain', Absent)
  1482.         path = standard.get('path', Absent)
  1483.         port = standard.get('port', Absent)
  1484.         expires = standard.get('expires', Absent)
  1485.         version = standard.get('version', None)
  1486.         if version is not None:
  1487.             version = int(version)
  1488.         
  1489.         secure = standard.get('secure', False)
  1490.         discard = standard.get('discard', False)
  1491.         comment = standard.get('comment', None)
  1492.         comment_url = standard.get('commenturl', None)
  1493.         if path is not Absent and path != '':
  1494.             path_specified = True
  1495.             path = escape_path(path)
  1496.         else:
  1497.             path_specified = False
  1498.             path = request_path(request)
  1499.             i = path.rfind('/')
  1500.             if i != -1:
  1501.                 if version == 0:
  1502.                     path = path[:i]
  1503.                 else:
  1504.                     path = path[:i + 1]
  1505.             
  1506.             if len(path) == 0:
  1507.                 path = '/'
  1508.             
  1509.         domain_specified = domain is not Absent
  1510.         domain_initial_dot = False
  1511.         if domain_specified:
  1512.             domain_initial_dot = bool(domain.startswith('.'))
  1513.         
  1514.         if domain is Absent:
  1515.             (req_host, erhn) = eff_request_host(request)
  1516.             domain = erhn
  1517.         elif not domain.startswith('.'):
  1518.             domain = '.' + domain
  1519.         
  1520.         port_specified = False
  1521.         if port is not Absent:
  1522.             if port is None:
  1523.                 port = request_port(request)
  1524.             else:
  1525.                 port_specified = True
  1526.                 port = re.sub('\\s+', '', port)
  1527.         else:
  1528.             port = None
  1529.         if expires is Absent:
  1530.             expires = None
  1531.             discard = True
  1532.         elif expires <= self._now:
  1533.             
  1534.             try:
  1535.                 self.clear(domain, path, name)
  1536.             except KeyError:
  1537.                 pass
  1538.  
  1539.             debug("Expiring cookie, domain='%s', path='%s', name='%s'", domain, path, name)
  1540.             return None
  1541.         
  1542.         return Cookie(version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest)
  1543.  
  1544.     
  1545.     def _cookies_from_attrs_set(self, attrs_set, request):
  1546.         cookie_tuples = self._normalized_cookie_tuples(attrs_set)
  1547.         cookies = []
  1548.         for tup in cookie_tuples:
  1549.             cookie = self._cookie_from_cookie_tuple(tup, request)
  1550.             if cookie:
  1551.                 cookies.append(cookie)
  1552.                 continue
  1553.         
  1554.         return cookies
  1555.  
  1556.     
  1557.     def make_cookies(self, response, request):
  1558.         '''Return sequence of Cookie objects extracted from response object.'''
  1559.         headers = response.info()
  1560.         rfc2965_hdrs = headers.getheaders('Set-Cookie2')
  1561.         ns_hdrs = headers.getheaders('Set-Cookie')
  1562.         rfc2965 = self._policy.rfc2965
  1563.         netscape = self._policy.netscape
  1564.         if not not rfc2965_hdrs or not ns_hdrs:
  1565.             if not not ns_hdrs or not rfc2965:
  1566.                 if (not rfc2965_hdrs or not netscape or not netscape) and not rfc2965:
  1567.                     return []
  1568.                 
  1569.         
  1570.         try:
  1571.             cookies = self._cookies_from_attrs_set(split_header_words(rfc2965_hdrs), request)
  1572.         except:
  1573.             reraise_unmasked_exceptions()
  1574.             cookies = []
  1575.  
  1576.         if ns_hdrs and netscape:
  1577.             
  1578.             try:
  1579.                 ns_cookies = self._cookies_from_attrs_set(parse_ns_headers(ns_hdrs), request)
  1580.             except:
  1581.                 reraise_unmasked_exceptions()
  1582.                 ns_cookies = []
  1583.  
  1584.             if rfc2965:
  1585.                 lookup = { }
  1586.                 for cookie in cookies:
  1587.                     lookup[(cookie.domain, cookie.path, cookie.name)] = None
  1588.                 
  1589.                 
  1590.                 def no_matching_rfc2965(ns_cookie, lookup = lookup):
  1591.                     key = (ns_cookie.domain, ns_cookie.path, ns_cookie.name)
  1592.                     return key not in lookup
  1593.  
  1594.                 ns_cookies = filter(no_matching_rfc2965, ns_cookies)
  1595.             
  1596.             if ns_cookies:
  1597.                 cookies.extend(ns_cookies)
  1598.             
  1599.         
  1600.         return cookies
  1601.  
  1602.     
  1603.     def set_cookie_if_ok(self, cookie, request):
  1604.         """Set a cookie if policy says it's OK to do so."""
  1605.         self._cookies_lock.acquire()
  1606.         self._policy._now = self._now = int(time.time())
  1607.         if self._policy.set_ok(cookie, request):
  1608.             self.set_cookie(cookie)
  1609.         
  1610.         self._cookies_lock.release()
  1611.  
  1612.     
  1613.     def set_cookie(self, cookie):
  1614.         '''Set a cookie, without checking whether or not it should be set.'''
  1615.         c = self._cookies
  1616.         self._cookies_lock.acquire()
  1617.         
  1618.         try:
  1619.             if cookie.domain not in c:
  1620.                 c[cookie.domain] = { }
  1621.             
  1622.             c2 = c[cookie.domain]
  1623.             if cookie.path not in c2:
  1624.                 c2[cookie.path] = { }
  1625.             
  1626.             c3 = c2[cookie.path]
  1627.             c3[cookie.name] = cookie
  1628.         finally:
  1629.             self._cookies_lock.release()
  1630.  
  1631.  
  1632.     
  1633.     def extract_cookies(self, response, request):
  1634.         '''Extract cookies from response, where allowable given the request.'''
  1635.         debug('extract_cookies: %s', response.info())
  1636.         self._cookies_lock.acquire()
  1637.         self._policy._now = self._now = int(time.time())
  1638.         for cookie in self.make_cookies(response, request):
  1639.             if self._policy.set_ok(cookie, request):
  1640.                 debug(' setting cookie: %s', cookie)
  1641.                 self.set_cookie(cookie)
  1642.                 continue
  1643.         
  1644.         self._cookies_lock.release()
  1645.  
  1646.     
  1647.     def clear(self, domain = None, path = None, name = None):
  1648.         '''Clear some cookies.
  1649.  
  1650.         Invoking this method without arguments will clear all cookies.  If
  1651.         given a single argument, only cookies belonging to that domain will be
  1652.         removed.  If given two arguments, cookies belonging to the specified
  1653.         path within that domain are removed.  If given three arguments, then
  1654.         the cookie with the specified name, path and domain is removed.
  1655.  
  1656.         Raises KeyError if no matching cookie exists.
  1657.  
  1658.         '''
  1659.         if name is not None:
  1660.             if domain is None or path is None:
  1661.                 raise ValueError('domain and path must be given to remove a cookie by name')
  1662.             
  1663.             del self._cookies[domain][path][name]
  1664.         elif path is not None:
  1665.             if domain is None:
  1666.                 raise ValueError('domain must be given to remove cookies by path')
  1667.             
  1668.             del self._cookies[domain][path]
  1669.         elif domain is not None:
  1670.             del self._cookies[domain]
  1671.         else:
  1672.             self._cookies = { }
  1673.  
  1674.     
  1675.     def clear_session_cookies(self):
  1676.         """Discard all session cookies.
  1677.  
  1678.         Note that the .save() method won't save session cookies anyway, unless
  1679.         you ask otherwise by passing a true ignore_discard argument.
  1680.  
  1681.         """
  1682.         self._cookies_lock.acquire()
  1683.         for cookie in self:
  1684.             if cookie.discard:
  1685.                 self.clear(cookie.domain, cookie.path, cookie.name)
  1686.                 continue
  1687.         
  1688.         self._cookies_lock.release()
  1689.  
  1690.     
  1691.     def clear_expired_cookies(self):
  1692.         """Discard all expired cookies.
  1693.  
  1694.         You probably don't need to call this method: expired cookies are never
  1695.         sent back to the server (provided you're using DefaultCookiePolicy),
  1696.         this method is called by CookieJar itself every so often, and the
  1697.         .save() method won't save expired cookies anyway (unless you ask
  1698.         otherwise by passing a true ignore_expires argument).
  1699.  
  1700.         """
  1701.         self._cookies_lock.acquire()
  1702.         now = time.time()
  1703.         for cookie in self:
  1704.             if cookie.is_expired(now):
  1705.                 self.clear(cookie.domain, cookie.path, cookie.name)
  1706.                 continue
  1707.         
  1708.         self._cookies_lock.release()
  1709.  
  1710.     
  1711.     def __iter__(self):
  1712.         return deepvalues(self._cookies)
  1713.  
  1714.     
  1715.     def __len__(self):
  1716.         '''Return number of contained cookies.'''
  1717.         i = 0
  1718.         for cookie in self:
  1719.             i = i + 1
  1720.         
  1721.         return i
  1722.  
  1723.     
  1724.     def __repr__(self):
  1725.         r = []
  1726.         for cookie in self:
  1727.             r.append(repr(cookie))
  1728.         
  1729.         return '<%s[%s]>' % (self.__class__, ', '.join(r))
  1730.  
  1731.     
  1732.     def __str__(self):
  1733.         r = []
  1734.         for cookie in self:
  1735.             r.append(str(cookie))
  1736.         
  1737.         return '<%s[%s]>' % (self.__class__, ', '.join(r))
  1738.  
  1739.  
  1740.  
  1741. class LoadError(Exception):
  1742.     pass
  1743.  
  1744.  
  1745. class FileCookieJar(CookieJar):
  1746.     '''CookieJar that can be loaded from and saved to a file.'''
  1747.     
  1748.     def __init__(self, filename = None, delayload = False, policy = None):
  1749.         '''
  1750.         Cookies are NOT loaded from the named file until either the .load() or
  1751.         .revert() method is called.
  1752.  
  1753.         '''
  1754.         CookieJar.__init__(self, policy)
  1755.         if filename is not None:
  1756.             
  1757.             try:
  1758.                 filename + ''
  1759.             raise ValueError('filename must be string-like')
  1760.  
  1761.         
  1762.         self.filename = filename
  1763.         self.delayload = bool(delayload)
  1764.  
  1765.     
  1766.     def save(self, filename = None, ignore_discard = False, ignore_expires = False):
  1767.         '''Save cookies to a file.'''
  1768.         raise NotImplementedError()
  1769.  
  1770.     
  1771.     def load(self, filename = None, ignore_discard = False, ignore_expires = False):
  1772.         '''Load cookies from a file.'''
  1773.         if filename is None:
  1774.             if self.filename is not None:
  1775.                 filename = self.filename
  1776.             else:
  1777.                 raise ValueError(MISSING_FILENAME_TEXT)
  1778.         
  1779.         f = open(filename)
  1780.         
  1781.         try:
  1782.             self._really_load(f, filename, ignore_discard, ignore_expires)
  1783.         finally:
  1784.             f.close()
  1785.  
  1786.  
  1787.     
  1788.     def revert(self, filename = None, ignore_discard = False, ignore_expires = False):
  1789.         """Clear all cookies and reload cookies from a saved file.
  1790.  
  1791.         Raises LoadError (or IOError) if reversion is not successful; the
  1792.         object's state will not be altered if this happens.
  1793.  
  1794.         """
  1795.         if filename is None:
  1796.             if self.filename is not None:
  1797.                 filename = self.filename
  1798.             else:
  1799.                 raise ValueError(MISSING_FILENAME_TEXT)
  1800.         
  1801.         self._cookies_lock.acquire()
  1802.         old_state = copy.deepcopy(self._cookies)
  1803.         self._cookies = { }
  1804.         
  1805.         try:
  1806.             self.load(filename, ignore_discard, ignore_expires)
  1807.         except (LoadError, IOError):
  1808.             self._cookies = old_state
  1809.             raise 
  1810.  
  1811.         self._cookies_lock.release()
  1812.  
  1813.  
  1814. from _LWPCookieJar import LWPCookieJar, lwp_cookie_str
  1815. from _MozillaCookieJar import MozillaCookieJar
  1816.